package mobilesmil.data;

import java.io.File;
import java.io.IOException;

import android.graphics.Canvas;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;

public class SmilAudioResource extends SmilResource implements OnPreparedListener{
	private MediaPlayer mPlayer;
	private boolean mPlayerLoaded = false; 
	
	public SmilAudioResource(String source, SmilRegion smilRegion, int beginTime, int endTime) {
		super(source, smilRegion, beginTime, endTime);
		super.setType("audio");
		mPlayer = new MediaPlayer();
		try {
			File tmpFile = new File(SmilResource.ROOT_PATH + source);
			if(tmpFile.exists()){
				mPlayer.setDataSource(SmilResource.ROOT_PATH + source);
				mPlayer.prepare();	//only call prepare when starting initial play.
				mPlayer.setOnPreparedListener(this);
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override public void play(Canvas canvas) {
		if(mPlayerLoaded && !mPlayer.isPlaying()){
			try {
				mPlayer.start();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			}
		}
	}

	@Override public void stop(Canvas canvas) {
		if(mPlayer != null)
		synchronized(mPlayer){
			if(mPlayer != null)
			if(mPlayer.isPlaying()){
				//mPlayer.stop();
				mPlayer.pause();
				mPlayer.seekTo(0);
				releaseMediaPlayer();
			}
		}
	}
	
	public void pause(){
		if(mPlayer.isPlaying() && mPlayerLoaded){
			try {
				mPlayer.pause();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			}
		}
	}

	@Override protected void finalize() throws Throwable {
		releaseMediaPlayer();
		super.finalize();
	}

	@Override public void onPrepared(MediaPlayer mp) {
		mPlayerLoaded = true;
		Log.d(getSource(), "Prepared");
	}

	private void releaseMediaPlayer() {
        if (mPlayer != null) {
            Log.d(getSource(), "releasing media");
            mPlayerLoaded = false;
            mPlayer.release();
            mPlayer = null;
        }
    }
}